import time

import numpy as np

from cion.emccd.camera import AcquisitionMode, EmccdCamera, ReadMode, Status, create_uint32_buffer


def capture_image(camera: EmccdCamera, *, exposure_time: float) -> np.ndarray:
    # set shift speeds & ad channels
    camera.set_as_fastest_recommended_vs_speed()
    camera.set_as_fastest_ad_channel_hs_speed(amplification=0)

    # baseline clamp
    if camera.support_baseline_clamp:
        camera.set_baseline_clamp(True)

    # set read mode & set image
    camera.set_read_mode(ReadMode.IMAGE)
    img_w, img_h = camera.get_detector_size()
    camera.set_image(hbin=1, vbin=1, hstart=0, hend=img_w, vstart=0, vend=img_h)
    img_size = img_w * img_h

    # set acquisition mode & exposure time
    camera.set_acquisition_mode(AcquisitionMode.SINGLE_SCAN)
    camera.set_exposure_time(exposure_time)

    # prepare buffer
    buffer = create_uint32_buffer(img_size)
    image = np.frombuffer(buffer, dtype=np.uint32).reshape((img_h, img_w))

    # capture
    camera.start_acquisition()
    while True:
        time.sleep(1)
        status = camera.get_status()
        if status == Status.IDLE:
            break
    camera.get_acquired_data(img_size, buffer)

    return image
